package config

import (
	"errors"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type Pgsql struct {
	GeneralDB `yaml:",inline" mapstructure:",squash"`
}

func (p *Pgsql) Dsn() string {
	return "host=" + p.Path + " user=" + p.Username + " password=" + p.Password + " dbname=" + p.Dbname + " port=" + p.Port + " " + p.Config
}

func (p *Pgsql) Db() (*gorm.DB, error) {
	if p.Dbname == "" {
		return nil, errors.New("dbname error")
	}
	pgsqlConfig := postgres.Config{
		DSN:                  p.Dsn(),
		PreferSimpleProtocol: false,
	}
	if db, err := gorm.Open(postgres.New(pgsqlConfig), &gorm.Config{}); err != nil {
		return nil, err
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(p.MaxIdleConns)
		sqlDB.SetMaxOpenConns(p.MaxOpenConns)
		return db, nil
	}
}
